/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.grnt.buddy;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.grnt.dbcommon.IdExtractor;
import org.grnt.dbcommon.DataControler.DataControlException;
import org.grnt.dbcommon.DataControler;
import static org.grnt.buddy.BuddiesContext.*;

/**
 *
 * It is a example servlet for illustrat how to implement add a group buddy semantic.
 * @author sayid
 */
public class AddBuddyGroupSlt extends HttpServlet {
	String ownerName = null;
	Long   ownerId   = null;
	String buddyPath = null;
	String msg = null;
	private Long buddyId;

	private void output(HttpServletResponse response) throws IOException {
		response.setContentType("text/html");
		response.setHeader("Pragma", "No-cache");
		response.setDateHeader("Expires", 0);
		response.setHeader("Cache-Control", "no-cache");
		ServletOutputStream out = response.getOutputStream();

		out.println("<head><title>Just a basic servlet</title></head>");
		out.println("<body>");
		out.println("owner name is: " + ownerName);
		out.println("<br/>");
		out.println("owner id is: " + ownerId);
		out.println("<br/>");
		out.println("BuddyPath is:" + buddyPath);
		out.println("<br/>");
		out.println("<H1>" + msg + "</H1>");
		out.println("</body>");
		out.close();
	}
	/**
	 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
	 * @param request servlet request
	 * @param response servlet response
	 * @throws ServletException if a servlet-specific error occurs
	 * @throws IOException if an I/O error occurs
	 */
	protected void processRequest(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
		ownerName = request.getParameter("ownerName");
		buddyPath = request.getParameter("buddyPath");
		if ((ownerName == null) || ("".equals(ownerName.trim()))) {
			msg = "Onwer name is empty.";
			output(response);
			return;
		}

		if ((buddyPath == null) || ("".equals(buddyPath.trim()))) {
			msg = "BuddyPath is empty.";
			output(response);
			return;
		}

		ownerName = ownerName.trim();
		buddyPath = buddyPath.trim();

		if ((ownerId = getUsersIndex().get(ownerName)) == null) {
			msg = "The owner name can't be found.";
			output(response);
			return;
		}

		String dirs[] = buddyPath.split("/");
		String path = null;
		Long parentId = null;
		try {
			for (String alias: dirs){
				path = (path == null) ? alias: path + "/" + alias;
				if (getBuddiesIndex().containsKey(path)) {
					parentId = getBuddiesIndex().get(path);
					continue;
				}
				parentId = addBuddy(alias, parentId);
			}
			msg = "successful.";
		} catch(DataControlException ex){
			Logger.getLogger(AddUserSlt.class.getName()).log(Level.SEVERE, null, ex);
			msg = ex.getMessage();
			ex.printStackTrace();
		} finally {
			output(response);
		}
	}

	private Long addBuddy(String alias, Long parentId) throws DataControlException {
		buddyId = IdExtractor.nextId("buddy_id");
		AddBuddy buddyUpdater = new AddBuddy(buddyId
			, alias
			, parentId
			, ownerId
			, null
			, true);
		DataControler.update(buddyUpdater);
		return buddyId;
	}

	// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
	/**
	 * Handles the HTTP <code>GET</code> method.
	 * @param request servlet request
	 * @param response servlet response
	 * @throws ServletException if a servlet-specific error occurs
	 * @throws IOException if an I/O error occurs
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * Handles the HTTP <code>POST</code> method.
	 * @param request servlet request
	 * @param response servlet response
	 * @throws ServletException if a servlet-specific error occurs
	 * @throws IOException if an I/O error occurs
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * Returns a short description of the servlet.
	 * @return a String containing servlet description
	 */
	@Override
	public String getServletInfo() {
		return "Short description";
	}// </editor-fold>

}
